package org.smartercontext.local.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.smartercontext.contextmger.contextsphere.ContextManagerController;
import org.smartercontext.contextmger.converters.RDFConverter;
import org.smartercontext.contextmger.fixedgatherers.FacebookGatherer;
import org.smartercontext.contextmger.fixedgatherers.ISocialGatherer;
import org.smartercontext.contextmger.json.reader.IJSONReader;
import org.smartercontext.contextmger.json.reader.JSONReader;

import com.hp.hpl.jena.rdf.model.Model;

/**
 * Servlet implementation class RedirectFBServlet
 */
@WebServlet("/RedirectFBServlet")
public class RedirectFBServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RedirectFBServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	HttpSession session = request.getSession();
        
        response.setContentType("text/html;charset=UTF-8");
        
        String code=request.getParameter("code");
        String token;
        
        if(code==null){
               response.sendRedirect("linkWith.jsp?Error=access_denied");         
        }else{
        	
        	if(code.equals("")){
        		response.sendRedirect("linkWith.jsp?Error=2");
        	}else{
        	
            try{
                
            String userGraph=FacebookGatherer.getURLUserGraph(code);
            
            if(userGraph.equals("Error")){
            	response.sendRedirect("linkWith.jsp");
            }
            
            URL url=new URL(userGraph);
            URLConnection connection=url.openConnection();
            BufferedReader reader=new BufferedReader(
                                      new InputStreamReader(
                                          connection.getInputStream()));
            String lineRead;
            StringBuffer buffer=new StringBuffer();
            
            while((lineRead = reader.readLine())!=null){
                buffer.append(lineRead).append("\n");  
            }
            reader.close();
            token=buffer.toString();
            
            if(token.startsWith("{")){
                throw new Exception("Error solicitando el token");
            }
            
            IJSONReader iLector=new JSONReader();
                        
            ISocialGatherer fG=new FacebookGatherer();
            
            JSONObject obj1=iLector.readJSONfromURL(fG.getBasicInformaction(token));
            JSONObject obj2=iLector.readJSONfromURL(fG.getEducationList(token));
            JSONObject obj3=iLector.readJSONfromURL(fG.getFriendList(token));
            JSONObject obj4=iLector.readJSONfromURL(fG.getFamilyList(token));
            JSONObject obj5=iLector.readJSONfromURL(fG.getMoviesList(token));
            JSONObject obj6=iLector.readJSONfromURL(fG.getMusicList(token));
            JSONObject obj7=iLector.readJSONfromURL(fG.getWorkList(token));
            JSONObject obj8=iLector.readJSONfromURL(fG.getBooksList(token));
            JSONObject obj9=iLector.readJSONfromURL(fG.getSignificantOther(token)); 
          
            fG.updateBasicInformation(obj1); //OK
            fG.updateSignificantOther(obj9); //OK
            fG.updateStudyInforrmatin(obj2); //OK 0
            fG.updateFamiliInformation(obj4); //OK 1
            fG.updateFriendsInformation(obj3);//OK 2
            fG.updateMoviesInformation(obj5); //OK 3
            fG.updateMusicInformation(obj6); //OK 4
            fG.updateBooksInformation(obj8); //OK 5
            fG.updateWorkInformation(obj7); //OK 6
            
            String username = (String) session.getAttribute("username");
        	System.err.println("*****"+username);
            
            if(session.getAttribute("username")!=null){
            	
            RDFConverter conv = new RDFConverter();
            Model userModel = ContextManagerController.getUsermodel(username);
            Model userModelModif = conv.writeFBContextInf(fG.getListaPreferencias()
            		,userModel
            		,fG.getFacebookId(), fG.getGenre(), fG.getBirthday()
            		,fG.getRelationShipStatus(), fG.getSignificantOther(), username);
            ContextManagerController.integrateContext(userModelModif, username);
            	
            }else{
            	response.sendRedirect("login.jsp?Err=3");
            }
                 
           response.sendRedirect("manageContext.jsp");
            
            }catch(Exception e){
            	
                response.sendRedirect("linkWith.jsp?Error=1");
            	//e.printStackTrace();
            }
        }  
            }
        }
  

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
